import os
import time

from django.http import HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
from django.core.paginator import Paginator
import matplotlib.pyplot as plt
from django.http import HttpResponse
from datetime import datetime

from .app import main_func
from .models import News


def news_list(request):
    newsList = News.objects.all()
    # 创建一个 Paginator 实例，每页显示 10 条数据
    paginator = Paginator(newsList, 10)
    # 获取当前页码，默认为第 1 页
    page_number = 1
    newsList = paginator.get_page(page_number)
    return render(request, 'news_list.html', {'newsList': newsList})


def newsById(request):
    news = News.objects.get(id=request.GET.get('id'))
    return render(request, 'news.html', {'news': news})


def my_view(request):
    # if not request.method == 'GET':
    # return HttpResponseBadRequest()
    data = {
        'name': 'John',
        'age': 30,
        'city': 'New York'
    }
    return JsonResponse(data, status=200, safe=False)


def newsByIds(request):
    news = News.objects.get(id=request.GET.get('id'))
    news_dict = {f'{field}': getattr(news, field) for field in ['title', 'content', 'num']}
    return JsonResponse(news_dict, json_dumps_params={'ensure_ascii': False}, status=200, safe=False, charset="utf-8")


def getDate():
    date_object = datetime.now()
    date_string = date_object.strftime("%Y%m%d")
    return date_string


"""
  python 词云
"""


def generate_image(request):
    image_data = main_func.do_image()
    # 生成图像的代码...
    fig, ax = plt.subplots()
    ax.imshow(image_data, cmap='gray')  # 将 image_data 替换为你的图像数据
    plt.axis('off')  # 关闭坐标轴
    times = time.time_ns()
    plt.savefig(str('demo/static/image/') + str(times) + str('.png'), bbox_inches='tight', pad_inches=0)  # 将图像保存为临时文件
    plt.close()
    with open('temp_image.png', 'rb') as image_file:
        return HttpResponse(image_file, content_type='image/png')  # 返回图像文件作


def get_image(request):
    # 文件名称
    times = getDate()
    url = str('demo/static/image/') + str(times) + str('.png')

    if os.path.exists(url):
        url = ".." + url.replace('demo', '')
        return render(request, 'news_word.html', {'url': url})
    else:
        image_data = main_func.do_image()
        # 生成图像的代码...
        fig, ax = plt.subplots()
        ax.imshow(image_data, cmap='gray')  # 将 image_data 替换为你的图像数据
        plt.axis('off')  # 关闭坐标轴
        plt.savefig(url, bbox_inches='tight', pad_inches=0)  # 将图像保存为临时文件
        plt.close()
        url = ".." + url.replace('demo', '')
        return render(request, 'news_word.html', {'url': url})

